<template>
  <el-dialog :title="`${showText}目录`" :visible="showDialog" @close="btnCancel" width="410px">
    <el-form :model="formData" :rules="rules" ref="addForm" label-width="120px">
      <el-form-item label="所属学科" prop="subjectID">
        <el-select v-model="formData.subjectID" @focus.native="subs" placeholder="请选择">
          <el-option v-for="item in subs" :key="item.id" :label="item.subjectName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="directoryName">
        <el-input v-model="formData.directoryName" style="width:88%" placeholder="请输入目录名称"/>
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="end">
      <el-button size="small" @click="btnCancel">取消</el-button>
      <el-button size="small" type="primary" @click="btnOK">确定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/directorys'
import { list } from '@/api/hmmm/subjects'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    directoryName: {
      type: String,
      default: null
    },
    subjectID: {
      type: [Number, String, Object],
      default: null
    }
  },
  data () {
    return {
      formData: {
        subjectID: '',
        directoryName: ''
      },
      rules: {
        directoryName: [{ required: true, message: '目录名称不能为空', trigger: 'blur' }],
        subjectID: [{ required: true, message: '所属学科不能为空', trigger: 'blur' }]
      },
      subs: []
    }
  },
  created () {
    this.simple()
    if (this.subjectID) {
      this.getDirectory({ id: this.subjectID })
    }
  },
  computed: {
    showText () {
      return this.formData.subjectID ? '修改' : '新增'
    }
  },
  methods: {
    async simple () {
      const { data } = await list()
      this.subs = data.items
    },
    async getDirectory (req) {
      const { data } = await detail(req)
      console.log(data)
      this.formData.subjectID = data.subjectID
      this.formData.directoryName = data.directoryName
    },
    async btnOK () {
      try {
        await this.$refs.addForm.validate()
        if (this.subjectID) {
          await update({ ...this.formData, id: this.subjectID })
          this.$message.success('修改目录成功')
        } else {
          await add(this.formData)
          this.$message.success('新增目录成功')
        }
        this.$emit('adds')
        this.btnCancel()
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    btnCancel () {
      this.$emit('update:showDialog', false)
      this.formData = {
        subjectID: '',
        directoryName: ''
      }
      this.$emit('update:subjectID', null)
      this.$refs.addForm.resetFields()
    }
  }
}
</script>

<style scoped lang='less'></style>
